import { ComponentClass } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image, Text, Button } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import bannerImg from '../../asset/images/step-apply-match/match-banner.jpg'
import notificationImg from '../../asset/images/step-apply-match/notific.png'
import { noConsole } from '../../config'
import ProductListItem from '../../components/product-list-item'
import Apply from '../../model/apply'

import './index.scss'
import { default as ApplyService } from '../../services/apply'
import Constants from '../../config/constants';

const applyService = new ApplyService()

// #region 书写注意
// 
// 目前 typescript 版本还无法在装饰器模式下将 Props 注入到 Taro.Component 中的 props 属性
// 需要显示声明 connect 的参数类型并通过 interface 的方式指定 Taro.Component 子类的 props
// 这样才能完成类型检查和 IDE 的自动提示
// 使用函数模式则无此限制
// ref: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/20796
//
// #endregion

type PageStateProps = {
  productList: any[],
  condition: any,           // 搜索条件
  userApplyList: Apply[],   // 用户身亲列表,
  checkedProducts: string[],    // 勾选的产品id数组 
}

type PageDispatchProps = {
  dispatchSave: (payload: any) => void,
  dispathcSearchFast: (condition: any) => void,
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface SetpApplyMatch {
  props: IProps;
  state: PageState;
}

@connect(({ stepApplyMatch, loading }) => ({
  ...stepApplyMatch,
  ...loading,
}), (dispatch) => ({
  dispatchSave(param: any) {
    dispatch({
      type: 'stepApplyMatch/save',
      payload: param
    })
  },
  dispathcSearchFast(condition) {
    dispatch({
      type: 'stepApplyMatch/searchFast',
      payload: condition
    })
  }
}))
class SetpApplyMatch extends Component {

  constructor(props) {
    super(props);
  }

  componentWillReceiveProps(nextProps) {
    
    // 显示加载中
    const searchLoading = nextProps.effects['stepApplyMatch/searchFast']
    if (searchLoading) {
      this._showLoadingCenter()
    } else {
      this._hideLoadingCenter()
    }

  }

  componentWillMount() { 
    // 获取url中的 deposit 参数
    const { deposit, time_limit } = this.$router.params
    // console.log(' this.$router.params = ',  this.$router.params)
    this.props.dispatchSave({
      condition: {
        deposit,
        time_limit,
      }
    })
  }

  componentDidMount() { 
    // 加载快速产品
    this.props.dispathcSearchFast(this.props.condition)

    this.initProductItemCheckWatch()
  }

  componentWillUnmount() {
    this.removeProductItemCheckWatch()
  }

  componentDidShow() { }

  componentDidHide() { }

  render() {
    const { productList } = this.props

    const products = productList.map(item => {
      return (<View className="product-item" key={item.product_id}>
        <ProductListItem
          product={item}
          isShowApply={false}
          isShowCheck={true}
          isShowCollectCancel={false}
          isShowLoanTime={true}
          userApplyList={this.props.userApplyList} />
      </View>)
    })

    return (
      <View className="match-product-apply-container">
        {/* <!-- 头部分块 --> */}
        <View className="header">
          <Image className="image" src={bannerImg}></Image>

          <View className="notification">
            <View className="content" hover-className="none" hover-stop-propagation="false">
              <Image className="image" src={notificationImg}></Image>
              <Text className="text">{productList.length > 0 ? '根据您的信息，我们为您匹配了以下产品' : '对不起，没有匹配的产品，请修改贷款额度等信息后重试'}</Text>
            </View>
          </View>
        </View>
        {/* <!-- 产品列表分块 --> */}
        <View className="product-list">
          {products}
        </View>
        {/* <!-- 底部按钮分块 --> */}
        <View className="bottom-box">
          <Button onClick={this.onSubmit}>提交</Button>
        </View>
      </View>
    )
  }

  /**
   * 提交选中产品的方法
   * @param {*} e 
   */
  onSubmit = (e) => {

    const { checkedProducts, condition } = this.props

    if (checkedProducts.length === 0) {
      Taro.showToast({
        title: '请选择产品后再提交',
        icon: 'none'
      })
      return
    }

    this._showLoadingCenter('提交中')

    const productIds = this.props.checkedProducts.map(item => item['product_id'])

    applyService.addFastProductOrders({
      loan_limit: condition.deposit,
      loan_date_limit: condition.time_limit,
    }, productIds).then(res => {
      this._hideLoadingCenter()
      if (res.code === 0) {
        const url = `/pages/stepApplyResult/index`
        Taro.navigateTo({
          url
        })
      }
    }, error => {
      console.error('批量提交快速产品有异常：', error)
      this._hideLoadingCenter()
    })
    // console.log('提交选中产品，products = ', this.data.checkedProducts)
  }

  /**
   * 监听产品列表组件的点击事件
   */
  initProductItemCheckWatch() {
    Taro.eventCenter.on(Constants.PRODUCT_LIST_ITEM_CHECK_EVENT, (param) => {
      const { checked, product } = param
      const { checkedProducts } = this.props
      
      const filterProducts = checkedProducts.filter(item => {
        return item['product_id'] !== product.product_id
      })

      if (checked) {
        filterProducts.push(product)
      }

      this.props.dispatchSave({
        checkedProducts: filterProducts
      })

    })
  }

  /**
   * 移除监听方法
   */
  removeProductItemCheckWatch() {
    Taro.eventCenter.off(Constants.PRODUCT_LIST_ITEM_CHECK_EVENT)
  }

  _showLoadingCenter(title?: string) {
    // 使用小程序的loading效果
    Taro.showLoading({
      title: title || '加载中',
      mask: true,
    })
  }

  _hideLoadingCenter() {
    Taro.hideLoading()
  }
}

// #region 导出注意
//
// 经过上面的声明后需要将导出的 Taro.Component 子类修改为子类本身的 props 属性
// 这样在使用这个子类时 Ts 才不会提示缺少 JSX 类型参数错误
//
// #endregion

export default SetpApplyMatch as ComponentClass<PageOwnProps, PageState>
